package com.edt.ichannel.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;

/**
 * httpclient上传文件
 * @author linwei
 *
 */
public class MultipartEntityUtil {
/**
 * 
 * @param filepath 本地文件地址
 * @param url 发送请求url
 * @param map参数map
 * @param charset编码
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
	public static String postFile(String filepath, String url, Map<String, String> map, String charset) throws ClientProtocolException, IOException {
		File file = new File(filepath);
		FileBody bin = null;
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		if(file != null) {
			bin = new FileBody(file);
		}
	    MultipartEntity reqEntity = new MultipartEntity();
	    Set<String> keySet = map.keySet();//获取map的key值的集合，set集合
		for(String obj:keySet){//遍历key
		    System.out.println("key:"+obj+",Value:"+map.get(obj));//输出键与值
		    StringBody element = new StringBody((String) map.get(obj),Charset.forName(charset));
		    reqEntity.addPart(obj, element);//text
		}
	    reqEntity.addPart("file", bin);//文件
	    httppost.setEntity(reqEntity);
	    HttpResponse response = httpclient.execute(httppost);
	    HttpEntity resEntity = response.getEntity();
	    StringBuffer rsp = new StringBuffer();
	    if (resEntity != null) {
		      InputStream in = resEntity.getContent();
		      BufferedReader reader = new BufferedReader(new InputStreamReader(in,charset));
				while (true) {
					String line = reader.readLine();
					if (line == null) {
						break;
					} else {
						rsp.append(line);
					}
				}
				reader.close();
				in.close();
		    }
		   
		    if (resEntity != null) {
		      resEntity.consumeContent();
		    }
		    System.out.println("返回数据"+rsp.toString());
		    return rsp.toString();
	}
}
  